import ChatMessage, { ChatMessageSenderReceiverType } from "../helper/chat/ChatMessage";
import networkutil from "../utils/network"

const searchContact = (userid?:string,searchedText?:string)=> {
    return networkutil.post("/chat/contact/search",{params:{
        userId:userid||"",
        keyword:searchedText||""
    }}).then((res:any)=>{
        return mapContactList(res.content.contactList);
    })
}

const addAcceptContact = (params:{userid:string,contactid:string,type:string})=>{
    return networkutil.post("/chat/contact/addaccept",{
        params:{
            userId:params.userid,
            contactId:params.contactid,
            type:params.type||"0"
        }
    }).then((res:any)=>{
        return res.content;
    })
}

const mapContactList = (contactList=[])=> {
    return contactList.map((item:any)=>{
        return {
            username:item.username,
            nickname:item.nickname,
            userid:item.userid,
            opstatus:item.opstatus,
            isContact:item.opstatus === 1,
            action:item.action || 0,
            tag:item.tag,
            contactAlias:item.contactalias,
            contactGroup:item.contactgroup,
        }
    });
}

const getContacts = (userid:string)=> {
    return networkutil.post("/chat/contact/list",{params:{userId:userid}}).then((res:any)=>{
        return mapContactList(res.content.contactList);
    });
}

const getGroupMembers = (groupId:string)=> {
    return networkutil.post("/chat/group/member/list",{params:{groupId}}).then((res:any)=>{
        return (res.content||{}).users
    });
}

const inviteGroupMember = (params:{
    raiserId:string,
    targetId:string,
    groupId:string,
})=>{
    return networkutil.post("/chat/group/invite",{params})
}

const acceptInviteToGroup = (params:{groupId:string,userId:string})=>{
    return networkutil.post("/chat/group/invite/opt",{params:{
        ...params,
        opt:'accept'
    }})
}

const rejectInviteToGroup = (params:{})=>{
    return networkutil.post("/chat/group/invite/opt",{params:{
        ...params,
        opt:'reject'
    }})
}

const addContactToGroup = (params:{groupId:string,adminId:string,contactId:string}) => {
    return networkutil.post("/chat/group/member/add",{params})
}

const deleteContact = (params:{ownerId:string,contactId:string}) => {
    return networkutil.post("/chat/contact/delete",{params:{
        ownerId:params.ownerId,
        contactId:params.contactId
    }})
}

const createNewGroup = (params:{
    adminId:string,
    groupName:string,
    groupTag:string,
    groupDesc?:string,
    channelId?:string,
    isPublic:boolean,
    memberMaxNumber:number
})=> {
    return networkutil.post("/chat/group/create",{params:{
        adminId:params.adminId,
        channelId:params.channelId,
        tag:params.groupTag,
        isPublic:params.isPublic,
        maxmemCount:params.memberMaxNumber,
        groupName:params.groupName,
        groupDesc:params.groupDesc
    }})
}

//get the channel groups or personal groups.
const getGroups = (params:{channelid?:string,userid?:string})=> {
    return networkutil.post("/chat/group/list",{params:{
        channelId:params.channelid,
        userId:params.userid
    }}).then((res:any)=>{
        return (res.content?.groups||[])
    })
}

const checkConversation = (params:{from:string,to?:string,groupid?:string})=>{
    return networkutil.post("/chat/conversation/query",{params:{
        from:params.from,
        to:params.to,
        groupid:params.groupid
    }})
}

/**
 * 
 * @param params 请求参数，当前用户id，对方用户id或者组id
 * @returns 
 */
const getConversations = (params:{fromid:string})=> {
    return networkutil.post("/chat/conversation/list",{
        params:{
            from:params.fromid,
        }
    }).then((res:any)=>{
        
        return ((res.content||{}).result||[]).map((item:any,idx:number)=>{
            // {
            //     name:"John",
            //     lastmsg:"Hello",
            //     lastmsgtime:"2024-01-01",
            //     "unreadmsgCount":2
            // },
            return {
                name:item.name||item.nickname,
                lastmsg:"",
                lastmsgtime:"",
                unreadmsgCount:"",
                cid:item.cid,
                from:item.from,
                to:item.to,
                status:item.status
            }
        })
    })
}

const getHistoryMessages = (params:{from:string,to:string,fromName:string,page:number})=> {
    return networkutil.post("/chat/msg/history",{params}).then((res:any)=>{
        return ((res.content||{}).messages||[]).map((message:any)=>{
            return new ChatMessage({
                fromNickName:message.nickname||params.fromName,
                from:message.from,
                toUser:message.to,
                messageId:message.msgId,
                message:message.message,
                createTime:message.createTime,
                avatarUrl:message.avatar,
                messageKind:message.messagetype,
                messageSenderReceiverType:message.from === params.from ? ChatMessageSenderReceiverType.receiver:ChatMessageSenderReceiverType.sender
            })
        })
    })
}

const getGroupHistoryMessages = (params:{groupId:string,userId:string,page:number})=> {
    return networkutil.post("/chat/group/msg/history",{params:{
        groupId:params.groupId,
        page:params.page
    }}).then((res:any)=>{
        return ((res.content||{}).messages||[]).map((message:any)=>{
            return new ChatMessage({
                fromNickName:message.nickname||message.username,
                from:message.from,
                toUser:message.to,
                messageId:message.msgId,
                message:message.message,
                createTime:message.createTime,
                avatarUrl:message.avatar,
                messageKind:message.messagetype,
                messageSenderReceiverType:message.from === params.userId ? ChatMessageSenderReceiverType.sender:ChatMessageSenderReceiverType.receiver
            })
        })
    })
}

const getChannels = ()=> {

}


const ChatService = {
    searchContact,
    addAcceptContact,
    getContacts,
    getGroupMembers,
    inviteGroupMember,
    acceptInviteToGroup,
    rejectInviteToGroup,
    addContactToGroup,
    deleteContact,
    getChannels,
    getConversations,
    checkConversation,
    createNewGroup,
    getGroups,
    getHistoryMessages,
    getGroupHistoryMessages
}


export default ChatService;
